package com.basic.business.common.shiro;

import com.basic.business.model.entity.SysMenu;
import com.basic.business.model.entity.SysRole;
import com.basic.business.service.SysMenuService;
import com.basic.business.service.SysRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public abstract class AbstractRealm extends AuthorizingRealm {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 进行权限验证
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        JwtEntity sysUserDto = (JwtEntity) SecurityUtils.getSubject().getPrincipal();
        List<SysRole> sysRoles = sysRoleService.findByLoginId(sysUserDto.getLoginId());
        List<String> roleIds = sysRoles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
        List<SysMenu> sysMenuList = sysMenuService.selectMenuByRoleIds(roleIds);
        Set<String> menuPaths = sysMenuList.stream().map(SysMenu::getMenuPath).collect(Collectors.toSet());

        Set<String> roleNames = sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.toSet());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 当前账号拥有的角色
        info.setRoles(roleNames);
        // 当前账号拥有的菜单权限
        info.setStringPermissions(menuPaths);
        return info;
    }



}